package com.woyou.service;

import java.io.Serializable;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;

import com.citaq.ideliver.R;
import com.google.gson.Gson;
import com.woyou.Constant;
import com.woyou.exception.NetException;

import android.content.Context;
import android.widget.Toast;
import retrofit.ErrorHandler;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RestAdapter.LogLevel;
import retrofit.RetrofitError;

/**
 * 网络接口服务(Service)的包装类
 * @author longtao.li
 */
@EBean
public class RetrofitWrapper {
	@RootContext Context context;
	private boolean isHandleError = true;
	
	RequestInterceptor requestInterceptor = new RequestInterceptor() {
		  @Override
		  public void intercept(RequestFacade request) {
		    request.addHeader("version", Constant.versionName);
		  }
	};

	public <T> T getNetService(Class<T> clazz) {
		String endpoint = Constant.SERVER;
		return getNetService(clazz, endpoint);
	}
	
	public <T> T getNetService(Class<T> clazz, String endPoiont) {
		RestAdapter ra = new RestAdapter.Builder()
			.setEndpoint(endPoiont)
			.setLogLevel(LogLevel.FULL)
			.setConverter(new GsonConverter(new Gson()))
//			.setErrorHandler(new RetrofitErrorHandler())
//			.setRequestInterceptor(requestInterceptor)
			.build();
		return ra.create(clazz);
	}

	public void setHandlerError(boolean isHandleError) {
		this.isHandleError = isHandleError;
	}

	class RetrofitErrorHandler implements ErrorHandler {
		@Override
		public Throwable handleError(RetrofitError error) {
			if (isHandleError) {
				String errorMsg = "";

				switch (error.getKind()) {
					case HTTP:
						ErrorMessageBean errorBean = (ErrorMessageBean) error.getBodyAs(ErrorMessageBean.class);
						errorMsg = errorBean.message;
						break;
					case NETWORK:
						errorMsg = context.getString(R.string.common_error_net);
						break;
					case CONVERSION:
						errorMsg = context.getString(R.string.common_error_conversion);
						break;
				}

				Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
			}
			return new NetException(error);
		}
	}

	public static class ErrorMessageBean implements Serializable {
		public String code;
		public String message;
	}
}
